package com.hup.vd.model.selenium;

import com.alibaba.fastjson.annotation.JSONField;
import com.hup.utils.commons.ListUtil;
import com.hup.utils.commons.io.BaseConfig;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * {@link #DEF_DESC}
 *
 * @author hugan
 * @date 2022/8/14
 */
@Data
@NoArgsConstructor
public class ChromeMessageMatcherConfig implements BaseConfig<ChromeMessageMatcherConfig> {

    private static final String DEF_DESC = "从Chrome的json字符串日志中匹配m3u8链接的配置;  "
            + "技巧说明:[\"str, str\"]实现startWith,endWith效果";

    private String desc = DEF_DESC;

    private List<MyCondition> conditions;

    public ChromeMessageMatcherConfig(List<MyCondition> conditions) {
        this.conditions = conditions;
    }

    public void init() {
        for (MyCondition condition : conditions) {
            condition.keys = condition.urlKeys.split("\\.");
        }
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class MyCondition {
        @Builder.Default
        public String url = "适用网址:to人工修改";
        public List<String> contains;
        /**
         * url所在的位置,如"message.params.response.url"
         */
        public String urlKeys;
        public String desc;
        /**
         * 代码中初始化和使用
         */
        @JSONField(serialize = false)
        public String[] keys;
    }

    @Override
    public boolean afterLoadFromFileOrReset(ChromeMessageMatcherConfig fileConfig) {
        if (isEmptyCondition()) {
            if (conditions == null) conditions = new ArrayList<>();
            conditions.clear();
            desc = DEF_DESC;
            conditions.add(MyCondition.builder()
                    .desc("第一个发出的m3u8请求")
                    .urlKeys("message.params.request.url")
                    .contains(Arrays.asList(
                            "Network.requestWillBeSent\"",//发出的请求,不管是否请求成功
                            "index.m3u8\""
                    )).build());
            return true;
        }
        return false;
    }

    private boolean isEmptyCondition() {
        if (ListUtil.nullOrEmpty(conditions)) return true;
        for (MyCondition condition : conditions) {
            if (condition != null && !ListUtil.nullOrEmpty(condition.contains)) return false;
        }
        return true;
    }
}
